package com.wh.wisdomsite.xbox.server;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.XboxLog;
import com.wh.wisdomsite.xbox.ba.service.IServiceMethodService;
import com.wh.wisdomsite.xbox.ba.service.IXboxLogService;
import com.wh.wisdomsite.xbox.pojo.ba.XboxLogIn;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Xbox日志表Controller
 * @Package com.wh.wisdomsite.xbox.server
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/xboxLog")
public class XboxLogController {

    private static final Log logger = LogFactory.getLog(XboxLogController.class);

    @Autowired
    private IXboxLogService iXboxLogService;

    @Autowired
    private IServiceMethodService iServiceMethodService;


    /**
     * 跳转页面到xboxLogList.jsp
     * @return
     */
    @RequiresPermissions("rules:dataServices_xboxLog_page")
    @RequestMapping(value = "index.do",method = RequestMethod.GET)
    public String index(){
        return "/dataServices/xboxLog/xboxLogList";
    }

    /**
     * 查询日志列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:dataServices_xboxLog_find")
    @RequestMapping(value = "/logList.do", method = RequestMethod.POST)
    public void showLogList(HttpServletResponse response, XboxLogIn in){
       try{
           logger.info("查询日志列表-->>开始");
           //设置分页
           if(in.getPage() == 0) in.setPage(1);
           if(in.getRows() == 0) in.setRows(10);
           Page<XboxLog> page = new Page<XboxLog>();
           page.setCurrent(in.getPage());
           page.setSize(in.getRows());
           EntityWrapper<XboxLog> ewXboxLog = new EntityWrapper<XboxLog>();
           ewXboxLog.setEntity(new XboxLog());
           //应用KEY
           if(StringUtils.isNotEmpty(in.getAppKey())){
               ewXboxLog.like("T_APP_KEY", in.getAppKey());
           }
           //服务方法
           if(StringUtils.isNotEmpty(in.getMethod())){
               ewXboxLog.like("T_METHOD", in.getMethod());
           }
           //手机号码
           if(StringUtils.isNotEmpty(in.getSessionPhone())){
               ewXboxLog.eq("T_SESSION_PHONE", in.getSessionPhone());
           }
           //用户名
           if(StringUtils.isNotEmpty(in.getSessionUserName())){
               ewXboxLog.eq("T_SESSION_USERNAME", in.getSessionUserName());
           }
           //调用结果
           if(null != in.getExecuteStatus()){
               ewXboxLog.eq("T_EXECUTE_STATUS", in.getExecuteStatus());
           }
           //执行结果
           if(StringUtils.isNotEmpty(in.getServiceCode())){
               if(Constants.CODE_SUCCESS.equalsIgnoreCase(in.getServiceCode())){
                   //执行成功
                   ewXboxLog.eq("T_SERVICE_CODE", in.getServiceCode());
               }else{
                   //执行失败
                   ewXboxLog.notIn("T_SERVICE_CODE", Constants.CODE_SUCCESS);
               }
           }
           //开始/结束时间
           if(StringUtils.isNotEmpty(in.getStartTime()) && StringUtils.isNotEmpty(in.getEndTime())){
               ewXboxLog.between("FROM_UNIXTIME(UNIX_TIMESTAMP(T_CREATE_DATE),'%Y-%m-%d %H:%i:%S')", in.getStartTime(), in.getEndTime());
           }
           //应用类型
           if(StringUtils.isNotEmpty(in.getCallType())){
               ewXboxLog.eq("T_CALL_TYPE", in.getCallType());
           }
           //应用平台
           if(StringUtils.isNotEmpty(in.getClient())){
               ewXboxLog.eq("T_CLIENT", in.getClient());
           }
           //客户端IP
           if(StringUtils.isNotEmpty(in.getIp())){
               ewXboxLog.eq("T_IP", in.getIp());
           }

           ewXboxLog.orderBy("T_CREATE_DATE", false);
           //获取XboxLog
           Page<XboxLog> xboxLogPage = iXboxLogService.selectPage(page, ewXboxLog);
           JSONObject json = new JSONObject();
           JSONArray array = new JSONArray();
           if(xboxLogPage.getRecords().size() > 0){
               for(XboxLog xboxLog : xboxLogPage.getRecords()){
                   JSONObject object = new JSONObject(xboxLog);
                   object.put("id", xboxLog.getId());
                   object.put("createDate", DateTool.format(xboxLog.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                   object.put("updateDate", DateTool.format(xboxLog.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
                   array.put(object);
               }
           }
           json.put("total",xboxLogPage.getTotal());
           json.put("rows",array);
           ResManager.getJsonOut(response).print(json);
           logger.info("查询日志列表-->>结束");
       } catch (Exception e){
           e.printStackTrace();
           logger.error("查询日志列表-->>Exception" + e.getMessage());
       }
    }

    /**
     * 请求日志详情
     * @param xboxLogIn
     * @param request
     * @return
     */
    @RequestMapping("xboxLogDesc.do")
    public String appSecretDesc(XboxLogIn xboxLogIn, HttpServletRequest request) {
        logger.info("请求日志详情-->>开始");
        //获取XboxLog
        XboxLog xboxLog = iXboxLogService.getById(xboxLogIn.getId());
        request.setAttribute("xboxLog", xboxLog);
        //获取ServiceMethod
        Map<String, String> serviceMethodMap = iServiceMethodService.getServiceMethodTitle();
        request.setAttribute("title",  serviceMethodMap.get(xboxLog.getMethod() + "$" + xboxLog.getVersion() + "$TITLE"));
        request.setAttribute("remark", serviceMethodMap.get(xboxLog.getMethod() + "$" + xboxLog.getVersion() + "$REMARK"));
        request.setAttribute("createDate", DateTool.format(xboxLog.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        request.setAttribute("updateDate", DateTool.format(xboxLog.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
        logger.info("请求日志详情-->>结束");
        return "/dataServices/xboxLog/xboxLogDesc";
    }

    /**
     * 查看日志记录
     * @param id
     * @return
     */
    @RequiresPermissions("rules:dataServices_xboxLog_view")
    @RequestMapping(value = "/logCurrentDetail.do", method = RequestMethod.GET)
    public String logCurrentDetail(String id, HttpServletRequest request) {
        try {
            logger.info("查看日志记录-->>开始");
            //获取XboxLog
            XboxLog xboxLog = iXboxLogService.getById(id);
            //获取ServiceMethod
            Map<String, String> serviceMethodMap = iServiceMethodService.getServiceMethodTitle();
            request.setAttribute("title",  serviceMethodMap.get(xboxLog.getMethod() + "$" + xboxLog.getVersion() + "$TITLE"));
            request.setAttribute("remark", serviceMethodMap.get(xboxLog.getMethod() + "$" + xboxLog.getVersion() + "$REMARK"));
            request.setAttribute("requestTime", DateTool.format(xboxLog.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
            request.setAttribute("xboxLog",xboxLog);

            //构建请求
            String contextPath = request.getContextPath();
            String client = xboxLog.getClient();
            String callType = xboxLog.getCallType();
            String callVersion = xboxLog.getCallVersion();
            String sessionId = StringUtils.stripToEmpty(xboxLog.getSessionId());
            String appKey = xboxLog.getAppKey();
            String method = xboxLog.getMethod();
            String version = xboxLog.getVersion();
            String format = xboxLog.getFormat();
            String sign = xboxLog.getSign();
            String bindObject = xboxLog.getBindObject().replaceAll("\r|\n|\t", "");
            String requestUrl = contextPath + "/service?client=" + client + "&callType=" + callType + "&callVersion=" + callVersion + "&appKey=" + appKey + "&method=" + method + "&version=" + version + "&format=" + format + "&sign=" + sign + "&sessionId=" + sessionId + "&bindObject=" + URLEncoder.encode(bindObject, "utf-8");
            request.setAttribute("requestUrl", requestUrl);

            logger.info("查看日志记录-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("查看日志记录-->>Exception" + e.getMessage());
        }
            return "/dataServices/xboxLog/xboxLogDetail";
    }
}
